package com.so.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.so.common.core.domain.BaseEntity;
import com.so.common.core.domain.model.LoginUser;
import com.so.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis-plus 自动填充
 * @author yhq
 */
@Slf4j
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof BaseEntity) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            this.setFieldValByName("createTime", new Date(), metaObject);
            if(null == loginUser){
                return;
            }
            this.setFieldValByName("createBy", loginUser.getUsername(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof BaseEntity) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            this.setFieldValByName("updateTime", new Date(), metaObject);
            if(null == loginUser){
                return;
            }
            this.setFieldValByName("updateBy", loginUser.getUsername(), metaObject);
        }
    }
}
